<?
class Email
{
	private $from, $message, $headers,$charset;
	/**
	 * Construct email class object
	 *
	 * @param string $from
	 * @param string $message
	 * @param string $contenttype
	 * @param string $charset
	 * TODO: Very weak class. Need update. The bat! headers using, because russian anti-spam engine (yandex.spamoborona) kill all other.
	 */
	public function __construct($from, $message, $contenttype = 'plain', $charset = null)
	{
		if($charset === null) $charset = Sslib::Variable('page.charset');
		$this->charset = $charset;
		$this->from = $from;
		$this->message = $message;
		$templ_end = "\r\n";
		if(Text::Lower($contenttype)=='html') $templ_end = '<br />'; 
		if(is_array($this->message))
		{
			$this->message = Email::MessageFromPost($this->message, "{name}: {value}".$templ_end);
			if(Text::Lower($contenttype) == 'html')
				$this->message = nl2br($this->message);
		
		}
		
		$this->headers = 
				'From: '.$this->from."\r\n".
				'Date: '.date('r')."\r\n".
				'MIME-Version: 1.0'."\r\n".
				'Content-transfer-encoding: 8bit'."\r\n".
				'Content-type: text/'.$contenttype.'; charset='.$charset."\r\n".
				'X-Mailer: The Bat! (v3.62.03) Professional'."\r\n".
				'Reply-To: '.$this->from."\r\n".
				"X-Priority: 3 (Normal)"."\r\n"
				;
		/*switch(strtoupper(substr(PHP_OS, 0, 3)))
		{
			
			case 'MAC':
				$this->headers = str_replace("\r\n", "\r", $this->headers);
				break;
			default: //'WIN':
				$this->headers = str_replace("\r\n", "\n", $this->headers);
				break;
		}*/
	}
	/*
	 * Create message from $_POST values
	 * 
	 * @param array $post
	 * @param string $template
	 * @param boolean $templateIsFile 
	 * 
	 */
	public static function MessageFromPost($post, $template, $templateIsFile = false)
	{
		$text = '';
		foreach($post as $key => $val)		
		{
			if(Text::Lower($key) == "submit") continue;
			$key = str_replace("_", " ",$key);
			if($templateIsFile)
				$text.=str_replace('{name}', $key,str_replace('{value}',$val,file_get_contents($template)));
			else
				$text.=str_replace('{name}', $key,str_replace('{value}',$val,$template));
		}
		return $text;
	}
	public function Send($to, $subject)
	{
		$message = $this->message;
		/*if(Sslib::Variable('page.charset') != $this->charset)
		{
			$subject = Text::Convert(Sslib::Variable('page.charset'), $this->charset, $subject);
			$message = Text::Convert(Sslib::Variable('page.charset'), $this->charset, $message);				
		}*/
		
		$to = trim(preg_replace('#[\n\r]+#s', '', $to));
		$subject = trim(preg_replace('#[\n\r]+#s', '', $subject));
		return mail($to, $subject, $message, $this->headers);
	}
	public static function ValidateAdress($email)
	{
		if(preg_match('/^[a-zA-Z0-9_\-.]+@(?:[a-zA-Z0-9_]{1,3})+(\.[a-zA-Z0-9_]{1,3})+(\.[a -zA-Z0-9_]{1,3})*/', $email))
			return true;
		else 
			return false;
	}
}	
?>